<?php

namespace api\sms\driver;

class Webchinese extends Sms
{

    // 错误码
    private array $errorCode = [
        '-1' => '没有该用户账户',
        '-2' => '接口密钥不正确',
        '-21' => 'MD5接口密钥加密不正确',
        '-3' => '短信数量不足',
        '-11' => '该用户被禁用',
        '-14' => '短信内容出现非法字符',
        '-4' => '手机号格式不正确',
        '-41' => '手机号码为空',
        '-42' => '短信内容为空',
        '-51' => '短信签名格式不正确',
        '-52' => '短信签名太长建议签名10个字符以内',
        '-6' => 'IP限制'
    ];


    /**
     * 发送短信
     *
     * @param string $phone 手机号
     * @param array $data 发送数据
     * @return bool
     */
    public function sendSms(string $phone, array $data): bool
    {
        try {
            $this->setContent($data['content']);
            $requestParams = [
                'Uid' => $this->config['webchinese_sms_account'] ?? '',
                'Key' => $this->config['webchinese_sms_key'] ?? '',
                'smsMob' => $phone,
                'smsText' => $data['content']
            ];

            $client = new \GuzzleHttp\Client();
            $response = $client->request('POST', 'https://utf8api.smschinese.cn/', [
                'verify' => app()->getRootPath() . 'cacert.pem',
                'form_params' => $requestParams
            ]);
            $params = json_decode($response->getBody(), true);
            $this->setSendStatus($params === 1);
            if ($params != 1) {
                $this->setErrorMessage($this->errorCode[$params] ?? '');
            }
        } catch (\Throwable $e) {
            $this->setSendStatus(false);
            $this->setErrorMessage('系统错误 ' . $e->getMessage());
        }

        return $this->getSendStatus();
    }
}